<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\plugin;

use app\common\plugin\PluginManager;

/**
 * 后台插件管理控制器
 */
class Manager extends Base
{
    protected $pluginManager;

    public function __construct()
    {
        parent::__construct();
        $this->pluginManager = new PluginManager();
    }

    /**
     * 获取插件列表
     */
    public function getList()
    {
        try {
            $page   = $this->request->get('page', 1);
            $limit  = $this->request->get('limit', 12);
            $search = $this->request->get('search', '');
            $status = $this->request->get('status', 'all');

            $plugins = $this->pluginManager->getInstalledPlugins();

            // 将对象转换为数组格式，以便前端处理
            $pluginList = [];
            foreach ($plugins as $pluginName => $plugin) {
                // 确保插件有必要的字段
                $plugin['plugin_name']  = $plugin['name'] ?? $pluginName;
                $plugin['display_name'] = $plugin['title'] ?? $plugin['name'] ?? $pluginName;

                // 状态过滤
                if ($status !== 'all') {
                    $isEnabled = isset($plugin['enabled']) ? $plugin['enabled'] : (isset($plugin['status']) ? $plugin['status'] : false);
                    if ($status === 'enabled' && !$isEnabled) {
                        continue;
                    }
                    if ($status === 'disabled' && $isEnabled) {
                        continue;
                    }
                }

                // 搜索过滤
                if (!empty($search)) {
                    $searchLower      = strtolower($search);
                    $displayNameLower = strtolower($plugin['display_name']);
                    $pluginNameLower  = strtolower($plugin['plugin_name']);
                    $descriptionLower = strtolower($plugin['short_description'] ?? $plugin['description'] ?? '');

                    if (
                        strpos($displayNameLower, $searchLower) === false &&
                        strpos($pluginNameLower, $searchLower) === false &&
                        strpos($descriptionLower, $searchLower) === false
                    ) {
                        continue;
                    }
                }

                $pluginList[] = $plugin;
            }

            // 计算分页
            $total         = count($pluginList);
            $totalPages    = ceil($total / $limit);
            $offset        = ($page - 1) * $limit;
            $paginatedList = array_slice($pluginList, $offset, $limit);

            return $this->success('获取成功', [
                'plugins'    => $paginatedList,
                'pagination' => [
                    'current_page' => (int) $page,
                    'total_pages'  => $totalPages,
                    'total_count'  => $total,
                    'has_prev'     => $page > 1,
                    'has_next'     => $page < $totalPages,
                    'per_page'     => (int) $limit
                ]
            ]);
        } catch (\Exception $e) {
            return $this->error('获取失败：' . $e->getMessage());
        }
    }

    /**
     * 启用插件
     */
    public function enable()
    {
        try {
            $pluginName = input('plugin_name');
            if (empty($pluginName)) {
                return $this->error('插件名称不能为空');
            }

            $result = $this->pluginManager->enablePlugin($pluginName);
            if ($result) {
                return $this->success('启用成功');
            } else {
                return $this->error('启用失败');
            }
        } catch (\Exception $e) {
            return $this->error('启用失败：' . $e->getMessage());
        }
    }

    /**
     * 禁用插件
     */
    public function disable()
    {
        try {
            $pluginName = input('plugin_name');
            if (empty($pluginName)) {
                return $this->error('插件名称不能为空');
            }

            $result = $this->pluginManager->disablePlugin($pluginName);
            if ($result) {
                return $this->success('禁用成功');
            } else {
                return $this->error('禁用失败');
            }
        } catch (\Exception $e) {
            return $this->error('禁用失败：' . $e->getMessage());
        }
    }

    /**
     * 卸载插件
     */
    public function uninstall()
    {
        try {
            $pluginName = input('plugin_name');
            if (empty($pluginName)) {
                return $this->error('插件名称不能为空');
            }

            $result = $this->pluginManager->uninstallPlugin($pluginName);
            if ($result) {
                return $this->success('卸载成功');
            } else {
                return $this->error('卸载失败');
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取插件配置
     */
    public function getConfig()
    {
        try {
            $pluginName = input('plugin_name');
            if (empty($pluginName)) {
                return $this->error('插件名称不能为空');
            }

            $config = $this->pluginManager->getPluginConfig($pluginName);
            return $this->success('获取成功', $config);
        } catch (\Exception $e) {
            return $this->error('获取失败：' . $e->getMessage());
        }
    }

    /**
     * 保存插件配置
     */
    public function saveConfig()
    {
        try {
            $request    = request();
            $pluginName = $request->post('plugin_name');

            if (empty($pluginName)) {
                return $this->error('插件名称不能为空');
            }

            // 检查插件是否有自己的管理入口
            $pluginInfo = $this->pluginManager->getPluginInfo($pluginName);
            if (!empty($pluginInfo['entry'])) {
                return $this->error('该插件有独立的管理页面，请使用插件自己的配置功能');
            }

            // 获取所有POST数据作为配置
            $config = $request->post();
            unset($config['plugin_name']); // 移除插件名称字段

            // 使用PluginManager统一保存配置，保持原结构
            $result = $this->pluginManager->savePluginConfig($pluginName, $config);
            if ($result) {
                return $this->success('保存成功');
            } else {
                return $this->error('保存失败');
            }
        } catch (\Exception $e) {
            return $this->error('保存失败：' . $e->getMessage());
        }
    }

    /**
     * 获取插件钩子列表
     */
    public function getHooks()
    {
        try {
            $pluginName = input('plugin_name');
            if (empty($pluginName)) {
                return $this->error('插件名称不能为空');
            }

            $hooks = $this->pluginManager->getPluginHooks($pluginName);
            return $this->success('获取成功', $hooks);
        } catch (\Exception $e) {
            return $this->error('获取失败：' . $e->getMessage());
        }
    }

    /**
     * 获取所有插件的钩子概览
     */
    public function getAllHooks()
    {
        try {
            $allHooks = $this->pluginManager->getAllPluginHooks();
            return $this->success('获取成功', $allHooks);
        } catch (\Exception $e) {
            return $this->error('获取失败：' . $e->getMessage());
        }
    }

    /**
     * 获取系统中所有已注册的钩子
     */
    public function getSystemHooks()
    {
        try {
            $systemHooks = $this->pluginManager->getSystemHooks();
            return $this->success('获取成功', $systemHooks);
        } catch (\Exception $e) {
            return $this->error('获取失败：' . $e->getMessage());
        }
    }

    /**
     * 禁用插件钩子
     */
    public function disableHook()
    {
        try {
            $pluginName = input('plugin_name');
            $hookName   = input('hook_name');

            if (empty($pluginName) || empty($hookName)) {
                return $this->error('插件名称和钩子名称不能为空');
            }

            $result = $this->pluginManager->disablePluginHook($pluginName, $hookName);
            if ($result) {
                return $this->success('钩子已禁用');
            } else {
                return $this->error('禁用失败');
            }
        } catch (\Exception $e) {
            return $this->error('禁用失败：' . $e->getMessage());
        }
    }

    /**
     * 启用插件钩子
     */
    public function enableHook()
    {
        try {
            $pluginName = input('plugin_name');
            $hookName   = input('hook_name');

            if (empty($pluginName) || empty($hookName)) {
                return $this->error('插件名称和钩子名称不能为空');
            }

            $result = $this->pluginManager->enablePluginHook($pluginName, $hookName);
            if ($result) {
                return $this->success('钩子已启用');
            } else {
                return $this->error('启用失败');
            }
        } catch (\Exception $e) {
            return $this->error('启用失败：' . $e->getMessage());
        }
    }

    /**
     * 删除插件钩子
     */
    public function deleteHook()
    {
        try {
            $pluginName = input('plugin_name');
            $hookName   = input('hook_name');

            if (empty($pluginName) || empty($hookName)) {
                return $this->error('插件名称和钩子名称不能为空');
            }

            $result = $this->pluginManager->deletePluginHook($pluginName, $hookName);
            if ($result) {
                return $this->success('钩子已删除');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 更新钩子优先级
     */
    public function updateHookPriority()
    {
        try {
            $pluginName   = input('plugin_name');
            $hookName     = input('hook_name');
            $handlerIndex = input('handler_index', 0);
            $priority     = input('priority', 10);

            if (empty($pluginName) || empty($hookName)) {
                return $this->error('插件名称和钩子名称不能为空');
            }

            $result = $this->pluginManager->updateHookPriority($pluginName, $hookName, $handlerIndex, $priority);
            if ($result) {
                return $this->success('优先级已更新');
            } else {
                return $this->error('更新失败');
            }
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

}
